﻿using MySql.Data.MySqlClient;
using OF.Lib.DataAccess.Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient; 
using System.Linq;
using System.Text;

namespace OF.Lib.DataAccess.Core
{
    public class DbConnConfigRandomImpl : IDbConnConfig
    {
        public DBConn GetDbConnConfig(bool isMasterDB, DBGroup groupConfig)
        {
            DBConn dbConnConfig = null;

            if (isMasterDB)
            {
                dbConnConfig = groupConfig.DBConnList.Find(f => f.MasterDB);
            }
            else
            {
                dbConnConfig = GetSlaveDbConnConfig(groupConfig);
            }

            return dbConnConfig;
        }

        public DBConn GetDbConnConfig(SQL sqlConfig, DBGroup groupConfig)
        {
            DBConn dbConnConfig = null;

            if (sqlConfig.IsMasterDB)
            {
                dbConnConfig = groupConfig.DBConnList.Find(f => f.MasterDB);
            }
            else
            {
                dbConnConfig = GetSlaveDbConnConfig(groupConfig);
            }

            return dbConnConfig;
        }

        private DBConn GetSlaveDbConnConfig(DBGroup groupConfig)
        {
            DBConn dbConnConfig = null;
            List<DBConn> slaveDBConnConfigList = groupConfig.DBConnList.FindAll(f => f.MasterDB == false);
            if (slaveDBConnConfigList == null || slaveDBConnConfigList.Count == 0)
            {
                throw new Exception(string.Format("SingleObject取Slave DB服务器，但是db.config中并未配置对应ConnKey={0}的Slave DB连接！",groupConfig.ConnKey));
            }
            //Jin：此处添加Salve DB的负载处理,在本实现类中取数量内的随机数
            int seed = Guid.NewGuid().GetHashCode();
            Random rand = new Random(seed);
            int i = rand.Next(1, slaveDBConnConfigList.Count + 1);
            dbConnConfig = slaveDBConnConfigList[i - 1];
            return dbConnConfig;
        }
    }
}
